package com.ccteam.admin.view.fragments.login

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.ccteam.admin.R
import com.ccteam.admin.databinding.FragmentLoginBinding
import com.ccteam.admin.utils.EventObserver
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.viewmodels.login.LoginViewModel
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@AndroidEntryPoint
class LoginFragment : Fragment() {

    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    private val loginViewModel by viewModels<LoginViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentLoginBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        loginViewModel.isLogin.observe(viewLifecycleOwner, {
            viewLifecycleOwner.lifecycleScope.launch {
                if(it){
                    findNavController().navigate(LoginFragmentDirections.actionLoginFragmentToMainFragment())
                } else {
                    binding.root.visibility = View.VISIBLE
                }
            }
        })

        loginViewModel.loadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnLogin.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Success){
                Snackbar.make(view,requireContext().getString(R.string.description_login_success), Snackbar.LENGTH_SHORT).show()
            } else if(it is LoadMessage.Error){
                Snackbar.make(view,it.errorMessage.description.toString(), Snackbar.LENGTH_SHORT).show()
            }
        })

        binding.btnLogin.setProgressButtonOnClickListener {
            loginViewModel.login(
                binding.editAccount.editText?.text.toString(),
                binding.editPassword.editText?.text.toString()
            )
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}